package com.xxl.sso.core.login;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.servlet.http.HttpSession;

import com.xxl.sso.core.conf.Conf.ThethirdConstant;
import com.xxl.sso.core.data.SsSsoCacheData;
import com.xxl.sso.core.entity.thethird.ThirdWebsiteInfo;
import com.xxl.sso.core.httpclient.SsSsoHttpClient;
import com.xxl.sso.core.login.session.SessionManager;

public class LogoutManager {

    public static void logout (String accessToken) {
        // 销毁与本系统相关的session
        Set<HttpSession> sessions = SessionManager.get(accessToken);
        if (sessions != null) {
            Iterator<HttpSession> sessionIterator = sessions.iterator();
            while (sessionIterator.hasNext()) {
                HttpSession session = sessionIterator.next();
                session.invalidate();
            }
            SessionManager.romove(accessToken);
        }

        // 通知其他系统执行登出操作
        Collection<ThirdWebsiteInfo> thirdWebsiteInfos = SsSsoCacheData.thethirdSystemMap.values();
        Iterator<ThirdWebsiteInfo> thirdWebsiteInfoIterator = thirdWebsiteInfos.iterator();
        while (thirdWebsiteInfoIterator.hasNext()) {
            ThirdWebsiteInfo thirdWebsiteInfo = thirdWebsiteInfoIterator.next();
            String tLogoutUrl = thirdWebsiteInfo.getCallbackLogoutUrl();

            Map<String, String> params = new HashMap<>();
            params.put(ThethirdConstant.SSO_ACCESS_TOKEN, accessToken);

            TLogoutExecutor.asynPost(tLogoutUrl, params);
        }
    }

    private static class TLogoutExecutor {
        private static final ExecutorService executor = Executors.newCachedThreadPool();

        public static void asynPost(final String url, final Map<String, String> params) {
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        String result = SsSsoHttpClient.getInstance().doPost(url, params);
                        System.out.println(result);
                    } catch (Exception e) {
                        System.out.println(e.getLocalizedMessage());
                    }
                }
            });
        }
    }
}
